import cv2
import numpy as np
import imutils
import time


def Img_Outline(img_path):
  original_img = cv2.imread(img_path)
  gray_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2GRAY)

  blurred = cv2.GaussianBlur(gray_img, (9, 9), 0)           # 高斯模糊去噪（设定卷积核大小影响效果）
  _, RedThresh = cv2.threshold(blurred, 160, 255, cv2.THRESH_BINARY) # 设定阈值165（阈值影响开闭运算效果）
  kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))     # 定义矩形结构元素
  closed = cv2.morphologyEx(RedThresh, cv2.MORPH_CLOSE, kernel)    # 闭运算（链接块）
  opened = cv2.morphologyEx(closed, cv2.MORPH_OPEN, kernel)      # 开运算（去噪点）
  return original_img, opened


def findContours_img(original_img, opened):
  contours = cv2.findContours(opened, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
  cnts = imutils.grab_contours(contours)
  # print(cnts)
  # c = sorted(cnts, key=cv2.contourArea, reverse=True)[0]     # 计算最大轮廓的旋转包围盒
  c = max(cnts, key=cv2.contourArea)
  rect = cv2.minAreaRect(c)
  # print(rect)
  angle = rect[2] # rect[2] 返回的是矩形的旋转角度
  print("angle", angle)
  if angle == 90.0:
    return original_img, original_img
  else:
    box = np.int0(cv2.boxPoints(rect))
    draw_img = cv2.drawContours(original_img.copy(), [box], -1, (0, 0, 255), 3)
    rows, cols = original_img.shape[:2]
    M = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle, 1)
    result_img = cv2.warpAffine(draw_img, M, (cols, rows))
    return result_img,draw_img


if __name__ == "__main__":
  img_path = '6.jpg'
  start_time = time.time()
  original_img, opened = Img_Outline(img_path)
  result_img,draw_img = findContours_img(original_img,opened)
  print('消耗的时间为：',(time.time() - start_time))

  cv2.imshow("original_img", original_img)
  cv2.imshow("draw_img", draw_img)
  cv2.imshow("result_img", result_img)
  cv2.waitKey(0)
  cv2.destroyAllWindows()